package com.leyou.sms.mq;

import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import static com.leyou.common.constants.MQConstants.*;
import java.util.Map;

/**
 * @Author: SGS
 * @Date : 2020/11/28 23:03
 * @Version :
 */
@Slf4j
@Component
public class MessageListener {

    private final SmsUtil smsUtil;

    public MessageListener(SmsUtil smsUtil) {
        this.smsUtil = smsUtil;
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QueueConstants.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = ExchangeConstants.SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = RoutingKeyConstants.VERIFY_CODE_KEY
    ))
    public void listenVerifyCodeMessage(Map<String,String> msg){
        //获取参数
        if (CollectionUtils.isEmpty(msg)){
            //消息为空不处理.
            return;
        }
        //手机号
        String phone= msg.get("phone");
        if (!RegexUtils.isPhone(phone)){
            return;
        }
        //验证码
        String code = msg.get("code");
        if (!RegexUtils.isCodeValid(code)){
            return;
        }
        //发送短信
        try {
            smsUtil.sendVerifyCode(phone,code);
        } catch (Exception e) {
            //短信发送失败,不重试
            log.error("短信验证码发送失败");
        }
    }
}
